package server;

import java.io.IOException;
import java.net.*;
import java.util.concurrent.*;

/**
 * A class that represents a server that takes clients requests
 * and handles them each on a separate thread.
 * 
 * @author Fredrik Bystam
 * @version 2011.10.17
 *
 */
public class RequestHandler {
	
	private final ExecutorService executor = Executors.newCachedThreadPool();
	private final int port;
	
	/**
	 * Create a new RequestHandler on a specific port.
	 * @param port The port to open a server on
	 */
	public RequestHandler (int port) {
		this.port = port;
	}
	
	/**
	 * Initialize the server and let it run until {@link RequestHandler.shutdown}
	 * is called or an uncaught exception is thrown.
	 * @throws IOException If an I/O error occurs on the serverSocket
	 */
	public void initialize () throws IOException {
		ServerSocket serverSocket = null;
		try {
			serverSocket = new ServerSocket(port);
			
			while (!executor.isShutdown()) {
				Socket client = null;
				try {
					client = serverSocket.accept();
					executor.execute(new ClientHandler(client));
				} finally {
					client.close();
				}
			}
			
		} finally {
			serverSocket.close();
		}
	}
	
	/**
	 * A safe shut down on the server.
	 */
	public void shutdown(){
		executor.shutdown();
	}
	
	/**
	 * A {link Runnable} that handles a client request.
	 * @author Fredrik Bystam
	 * @version 2011.10.17
	 * 
	 */
	private static class ClientHandler implements Runnable {

		private final Socket client;
		
		public ClientHandler(Socket client) {
			this.client = client;
		}
		
		@Override public void run() {
			// TODO What the fuck to do with the client goes here
		}
	}
}
